/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Form;

import data.Column;
import data.ManagerDatabase;
import data.Row;
import data.Table;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.text.Position;
import javax.swing.tree.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import sqlcommand.MyError;

/**
 *
 * @author GREENWIND
 */
public class FormMain extends javax.swing.JFrame {

    public ImageIcon iconLeaf = new ImageIcon(getClass().getResource("/Form/img/leaf.png"));
    public ImageIcon iconTable = new ImageIcon(getClass().getResource("/Form/img/table.png"));
    public ImageIcon iconOpen = new ImageIcon(getClass().getResource("/Form/img/open.png"));
    public ImageIcon iconClose = new ImageIcon(getClass().getResource("/Form/img/close.png"));
    public ImageIcon iconKey = new ImageIcon(getClass().getResource("/Form/img/key.png"));

    /**
     * Creates new form FormMain
     */
    public FormMain() {
        super("JSQL Server Phiên bản dùng thử---Edit by Phạm Trần Thanh Phong vd Nguyễn Văn Quang");
        initComponents();
        initJTree();
        initJTabedPane();
        ListDatabase = new ArrayList<ManagerDatabase>();

    }

    public void initJTree() {
        DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
        renderer.setLeafIcon(iconLeaf);
        renderer.setOpenIcon(iconOpen);
        renderer.setClosedIcon(iconClose);
        treeDatabase.setCellRenderer(renderer);
        treeDatabase.repaint();
    }

    public void initJTabedPane() {
        tabpane1.setTabComponentAt(tabNumbers,
                new TabbedTable("Welcome", tabpane1, null));
    }

    public void createNewTab(String tabName, String database) {
        tabpane1.setTabComponentAt(tabpane1.getTabCount(), new TabbedTable(tabName, tabpane1, database));
    }

    public void createNewDataBase(String nodeName) {
        DefaultMutableTreeNode nNode = new DefaultMutableTreeNode(nodeName);
        DefaultMutableTreeNode table = new DefaultMutableTreeNode("Table");
        DefaultMutableTreeNode primaryKey = new DefaultMutableTreeNode("Primary Key");
        nNode.add(table);
        nNode.add(primaryKey);
        TreePath path = treeDatabase.getNextMatch("My Database", 0, Position.Bias.Forward);
        MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();
        DefaultTreeModel model = (DefaultTreeModel) treeDatabase.getModel();
        model.insertNodeInto(nNode, node, node.getChildCount());
        treeDatabase.setCellRenderer(new MyRenderer(iconLeaf, iconTable, iconOpen, iconClose, iconKey, ListDatabase));
    }

    public Boolean createNewNodeTable(String nodeName, TreePath jtable) {
        DefaultMutableTreeNode nNode = new DefaultMutableTreeNode(nodeName);
        MutableTreeNode node = (MutableTreeNode) jtable.getLastPathComponent();
        DefaultTreeModel model = (DefaultTreeModel) treeDatabase.getModel();


        TreePath dat = jtable.getParentPath();
        Object[] o = dat.getPath();
        for (int i = 0; i < ListDatabase.size(); i++) {
            if (ListDatabase.get(i).GetName().equals(o[o.length - 1].toString())) {
                Table tb = new Table(nodeName);
                if (ListDatabase.get(i).addNewTable(tb)) {
                    model.insertNodeInto(nNode, node, node.getChildCount());
                    return true;
                }

            }
        }
        return false;

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        bt_Open = new javax.swing.JButton();
        bt_Save = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txt_output = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        treeDatabase = new javax.swing.JTree(myDatabase);
        tabpane1 = new javax.swing.JTabbedPane();
        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        item_newdatabase = new javax.swing.JMenuItem();
        Item_Exit = new javax.swing.JMenuItem();
        jMenu7 = new javax.swing.JMenu();
        item_inserttable = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        itemCreateConnect = new javax.swing.JMenuItem();
        disconnect = new javax.swing.JMenuItem();
        jMenu5 = new javax.swing.JMenu();
        jMenu6 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setRollover(true);

        bt_Open.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Form/img/bt-open.png"))); // NOI18N
        bt_Open.setFocusable(false);
        bt_Open.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_Open.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_Open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_OpenActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_Open);

        bt_Save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Form/img/disk.png"))); // NOI18N
        bt_Save.setFocusable(false);
        bt_Save.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_Save.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_Save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_SaveActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_Save);

        jTabbedPane1.setBackground(new java.awt.Color(102, 102, 255));
        jTabbedPane1.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
        jTabbedPane1.setToolTipText("");
        jTabbedPane1.setMaximumSize(new java.awt.Dimension(105, 123));

        txt_output.setColumns(20);
        txt_output.setEditable(false);
        txt_output.setRows(5);
        txt_output.setText("Not Established");
        jScrollPane1.setViewportView(txt_output);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 657, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Status socket", jPanel1);

        treeDatabase.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                treeDatabaseMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                treeDatabaseMouseReleased(evt);
            }
        });
        jScrollPane2.setViewportView(treeDatabase);

        jButton1.setText("Execute");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jMenuBar1.add(jMenu2);

        jMenu3.setText("File");

        item_newdatabase.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        item_newdatabase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Form/img/new.png"))); // NOI18N
        item_newdatabase.setText("New DataBase");
        item_newdatabase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                item_newdatabaseActionPerformed(evt);
            }
        });
        jMenu3.add(item_newdatabase);

        Item_Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.ALT_MASK));
        Item_Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Form/img/im_close.png"))); // NOI18N
        Item_Exit.setText("Exit");
        Item_Exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Item_ExitActionPerformed(evt);
            }
        });
        jMenu3.add(Item_Exit);

        jMenuBar1.add(jMenu3);

        jMenu7.setText("Table");

        item_inserttable.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_MASK));
        item_inserttable.setText("Insert Table");
        item_inserttable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                item_inserttableActionPerformed(evt);
            }
        });
        jMenu7.add(item_inserttable);

        jMenuBar1.add(jMenu7);

        jMenu1.setText("Connection");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu1ActionPerformed(evt);
            }
        });

        itemCreateConnect.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK));
        itemCreateConnect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Form/img/connection.png"))); // NOI18N
        itemCreateConnect.setText("Create Connection");
        itemCreateConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemCreateConnectActionPerformed(evt);
            }
        });
        jMenu1.add(itemCreateConnect);

        disconnect.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        disconnect.setText("Disconnect");
        disconnect.setEnabled(false);
        disconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                disconnectActionPerformed(evt);
            }
        });
        jMenu1.add(disconnect);

        jMenuBar1.add(jMenu1);

        jMenu5.setText("About");
        jMenuBar1.add(jMenu5);

        jMenu6.setText("Help");
        jMenuBar1.add(jMenu6);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 568, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2)
                        .addGap(18, 18, 18)
                        .addComponent(tabpane1, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(24, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 436, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tabpane1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jButton1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void item_newdatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_item_newdatabaseActionPerformed
        // TODO add your handling code here:
        newdatabase = JOptionPane.showInputDialog(null, "Enter name database : ",
                "New Database", WIDTH);
        if (!newdatabase.equals("")) {
            newdatabase = newdatabase.toUpperCase();
            JOptionPane.showMessageDialog(null, "Create database " + newdatabase + " success",
                    "Success", 1);
            createNewDataBase(newdatabase);
            ManagerDatabase newdata = new ManagerDatabase(newdatabase);
            ListDatabase.add(newdata);
        }
    }//GEN-LAST:event_item_newdatabaseActionPerformed

    private void Item_ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Item_ExitActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_Item_ExitActionPerformed

    private void item_inserttableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_item_inserttableActionPerformed
        // TODO add your handling code here:
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeDatabase.getLastSelectedPathComponent();
        Object o = ((DefaultMutableTreeNode) node).getUserObject();
        TreeNode parent = node.getParent();
        if (o.toString().equals("Table")) {
            newtable = JOptionPane.showInputDialog(null, "Enter name table : ",
                    "New Table", 1);
            if (newtable != null) {
                // ListDatabase.add(newdatabase);
                newtable = newtable.toUpperCase();

                TreePath jtable = treeDatabase.getAnchorSelectionPath();
                if (createNewNodeTable(newtable, jtable)) {
                    JOptionPane.showMessageDialog(null, "Create table " + newtable + " success",
                            "Success", 1);
                    createNewTab(newtable, parent.toString());
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Fail: Exist table " + newtable,
                            "Fail", 1);
                }


            }
        }

    }//GEN-LAST:event_item_inserttableActionPerformed

    private void itemCreateConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemCreateConnectActionPerformed
        try {
            // TODO add your handling code here:
            port = JOptionPane.showInputDialog(null, "Enter port: ",
                    "Create socket", 1);
            if ("".equals(port)) {
                return;
            }
            if (port == null) {
                return;
            }
            sv = new ServerSocket(Integer.parseInt(port));
            disconnect.setEnabled(true);
            Thread thread_server = new Thread(new Runnable() {

                public void run() {
                    try {
                        txt_output.setText("Waiting client connect...");
                        Server = sv.accept();
                        ois = new ObjectInputStream(Server.getInputStream());
                        oos = new ObjectOutputStream(Server.getOutputStream());
                        ArrayList<String> datname = new ArrayList<>();
                        for (int i = 0; i < ListDatabase.size(); i++) {
                            datname.add(ListDatabase.get(i).GetName());
                        }
                        txt_output.setText("Connected client with IP " + Server.getInetAddress().getHostAddress() + "\n");
                        oos.writeObject(datname);
                        oos.flush();
                        while (Server.isConnected()) {
                            String dat = (String) ois.readObject();
                            String query = (String) ois.readObject();
                            SetStatus("Received object from client\n");
                            ManagerDatabase md = null;
                            for (int i = 0; i < ListDatabase.size(); i++) {
                                if (ListDatabase.get(i).GetName().equals(dat)) {
                                    md = ListDatabase.get(i);
                                }
                            }

                            MyError err = new MyError();
                            ArrayList<Row> rows = md.sqlExcute(query, err);
                            if(rows == null){
                                SetStatus(err.getError());
                            }
                            ObjectSocket o = new ObjectSocket(rows, err.getError());
                            int size = rows.size();
                            oos.writeObject(size);
                            oos.flush();
                            for(int i = 0; i < size;i++)
                            {
                                oos.writeObject(rows.get(i));
                                oos.flush();
                            }
                            oos.reset();
                            //oos.writeObject(rows);
                            System.out.println(o.getRow().size());
                            if(o.getRow().size() == 4)
                                System.out.println(o.getRow().get(3).getListCell().get(0).getData());
                            SetStatus("Sent object to client\n");
                        }

                    } catch (IOException | ClassNotFoundException ex) {
                        ex.printStackTrace();
                               
     
                    }
                }
            });
            thread_server.start();
        } catch (IOException ex) {
            Logger.getLogger(FormMain.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_itemCreateConnectActionPerformed

    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed
        // TODO add your handling code here:
        JOptionPane.showMessageDialog(rootPane,
                "create", "Success", WIDTH);
    }//GEN-LAST:event_jMenu1ActionPerformed

    private void treeDatabaseMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeDatabaseMouseReleased
        // TODO add your handling code here:
        try {
            popup = new JPopupMenu();
            final DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeDatabase.getLastSelectedPathComponent();
            final TreeNode parent = node.getParent();
            final Object o = ((DefaultMutableTreeNode) node).getUserObject();
            switch (o.toString()) {
                case "My Database": {
                    mi = new JMenuItem("New DataBase");
                    mi.addActionListener(new java.awt.event.ActionListener() {

                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                            item_newdatabaseActionPerformed(evt);
                        }
                    });
                    popup.add(mi);
                    break;
                }
                case "Table": {
                    mi = new JMenuItem("Insert Table");
                    mi.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
                    mi.addActionListener(new java.awt.event.ActionListener() {

                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                            item_inserttableActionPerformed(evt);
                        }
                    });
                    popup.add(mi);
                    break;
                }
                default: {
                    if (parent.toString().equals("Table")) {
                        final TreeNode dat = parent.getParent();
                        mi = new JMenuItem("Open data");
                        mi.addActionListener(new java.awt.event.ActionListener() {

                            public void actionPerformed(java.awt.event.ActionEvent evt) {
                                //  tabpane1.setTabComponentAt(tabpane1.getTabCount(), new AddData(o.toString(), tabpane1, dat.toString()));
                                AddData data = new AddData(o.toString(), dat.toString());
                                data.setVisible(true);
                                data.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
                                data.pack();
                            }
                        });

                        delete = new JMenuItem("Delete");
                        delete.addActionListener(new java.awt.event.ActionListener() {

                            public void actionPerformed(java.awt.event.ActionEvent evt) {
                                DefaultTreeModel model = (DefaultTreeModel) treeDatabase.getModel();
                                TreePath path = treeDatabase.getNextMatch(o.toString(), 0, Position.Bias.Forward);
                                MutableTreeNode mNode = (MutableTreeNode) path.getLastPathComponent();
                                model.removeNodeFromParent(mNode);
                                for (int i = 0; i < ListDatabase.size(); i++) {
                                    if (parent.getParent().toString().equals(ListDatabase.get(i).GetName())) {
                                        if (ListDatabase.get(i).deleteTable(o.toString())) {
                                            JOptionPane.showMessageDialog(rootPane,
                                                    "Xoa thanh cong", "Success", WIDTH);
                                        }
                                    }
                                }
                            }
                        });
                        popup.add(mi);
                        popup.add(delete);
                    } else {
                        mi = null;
                        delete = new JMenuItem("Close");
                        delete.addActionListener(new java.awt.event.ActionListener() {

                            public void actionPerformed(java.awt.event.ActionEvent evt) {
                                for (int i = 0; i < ListDatabase.size(); i++) {
                                    if (o.toString().equals(ListDatabase.get(i).GetName())) {
                                        ListDatabase.remove(i);
                                    }
                                }
                                DefaultTreeModel model = (DefaultTreeModel) treeDatabase.getModel();
                                TreePath path = treeDatabase.getNextMatch(o.toString(), 0, Position.Bias.Forward);
                                MutableTreeNode mNode = (MutableTreeNode) path.getLastPathComponent();
                                model.removeNodeFromParent(mNode);
                            }
                        });
                        popup.add(delete);
                    }
                    break;
                }
            }
            popup.setOpaque(true);
            popup.setLightWeightPopupEnabled(true);
            if (evt.isPopupTrigger()) {
                popup.show((JComponent) evt.getSource(), evt.getX(), evt.getY());
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_treeDatabaseMouseReleased

    private void treeDatabaseMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeDatabaseMousePressed
        // TODO add your handling code here:
        try {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeDatabase.getLastSelectedPathComponent();
            Object o = ((DefaultMutableTreeNode) node).getUserObject();
            TreeNode parent = node.getParent();
            if (evt.getClickCount() == 2 && parent.toString().equals("Table")) {
                createNewTab(o.toString(), parent.getParent().toString());
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_treeDatabaseMousePressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        try {
            TabbedTable tab;
            tab = (TabbedTable) tabpane1.getTabComponentAt(tabpane1.getSelectedIndex());
            if (tab.tabName().equals("Welcome")) {
                return;
            }

            if (!tab.InputCorrect()) {
                JOptionPane.showMessageDialog(rootPane,
                        "Nhap cot nhap bi loi", "Success", WIDTH);
                return;
            }
            ArrayList<Column> cols = new ArrayList<>();
            cols = tab.getDataCol();
            for (int j = 0; j < ListDatabase.size(); j++) {
                if (tab.getDatabase().equals(ListDatabase.get(j).GetName())) {
                    ListDatabase.get(j).getTable(tab.tabName()).getListCol().clear();
                    for (int k = 0; k < cols.size(); k++) {
                        ListDatabase.get(j).getTable(tab.tabName()).insertColumn(cols.get(k));
                    }
                    break;
                }
            }
            JOptionPane.showMessageDialog(rootPane,
                    "Create column " + tab.tabName() + " success", "Success", WIDTH);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void bt_OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_OpenActionPerformed
        // TODO add your handling code here:
        OpenData open = new OpenData();

        ManagerDatabase loaddat = open.getDataBase();
        if (loaddat == null) {
            return;
        }
        ListDatabase.add(loaddat);
        treeDatabase.setCellRenderer(new MyRenderer(iconLeaf, iconTable, iconOpen, iconClose, iconKey, ListDatabase));
        addJTree(loaddat);
    }//GEN-LAST:event_bt_OpenActionPerformed
    private void addJTree(ManagerDatabase loaDatabase) {
        DefaultMutableTreeNode nNode = new DefaultMutableTreeNode(loaDatabase.GetName());
        DefaultMutableTreeNode table = new DefaultMutableTreeNode("Table");
        DefaultMutableTreeNode primaryKey = new DefaultMutableTreeNode("Primary Key");
        nNode.add(table);
        nNode.add(primaryKey);
        TreePath path = treeDatabase.getNextMatch("My Database", 0, Position.Bias.Forward);

        MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();
        DefaultTreeModel model = (DefaultTreeModel) treeDatabase.getModel();
        model.insertNodeInto(nNode, node, node.getChildCount());

        for (int i = 0; i < loaDatabase.getAllTables().size(); i++) {
            DefaultMutableTreeNode tbNode = new DefaultMutableTreeNode(loaDatabase.getAllTables().get(i).getTableName());
            model.insertNodeInto(tbNode, table, table.getChildCount());
        }
    }
    private void bt_SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_SaveActionPerformed
        // TODO add your handling code here:
        if (ListDatabase.isEmpty()) {
            return;
        }
        for (int i = 0; i < ListDatabase.size(); i++) {
            SaveData save = new SaveData(ListDatabase.get(i));
            save.Save();
        }

    }//GEN-LAST:event_bt_SaveActionPerformed

    private void disconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disconnectActionPerformed

        // TODO add your handling code here:
        Thread thread_server = new Thread(new Runnable() {

            public void run() {
                try {
                    oos.close();
                    ois.close();
                    Server.close();
                    SetStatus("Close Socket\n");
                } catch (IOException ex) {
                    Logger.getLogger(FormMain.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        thread_server.start();

    }//GEN-LAST:event_disconnectActionPerformed
    public static String getCurrentTimeStamp() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    }

    public void SetStatus(String status) {
        String str_cur = txt_output.getText();
        txt_output.setText(str_cur + getCurrentTimeStamp() + ": " + status);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            /*
             * Set the Nimbus look and feel
             */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
             * If Nimbus (introduced in Java SE 6) is not available, stay with
             * the default look and feel. For details see
             * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */
            // UIManager.setLookAndFeel("com.easynth.lookandfeel.EaSynthLookAndFeel");
            UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");
            //  UIManager.setLookAndFeel(ch.randelshofer.quaqua.QuaquaManager.getLookAndFeel());

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FormMain.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(FormMain.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(FormMain.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(FormMain.class.getName()).log(Level.SEVERE, null, ex);
        }
//</editor-fold>
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                FormMain f = new FormMain();
                f.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem Item_Exit;
    private javax.swing.JButton bt_Open;
    private javax.swing.JButton bt_Save;
    private javax.swing.JMenuItem disconnect;
    private javax.swing.JMenuItem itemCreateConnect;
    private javax.swing.JMenuItem item_inserttable;
    private javax.swing.JMenuItem item_newdatabase;
    private javax.swing.JButton jButton1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenu jMenu7;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTabbedPane tabpane1;
    private javax.swing.JTree treeDatabase;
    private javax.swing.JTextArea txt_output;
    // End of variables declaration//GEN-END:variables
    private String newdatabase;
    private String newtable;
    DefaultMutableTreeNode myDatabase = new DefaultMutableTreeNode("My Database");
    DefaultMutableTreeNode child = new DefaultMutableTreeNode("My child");
    public static ArrayList<ManagerDatabase> ListDatabase;
    JPopupMenu popup;
    JMenuItem mi;
    JMenuItem delete;
    int tabNumbers = 0;
    //Socket
    public ServerSocket sv;
    public String port;
    public Socket Server;
    InputStream in;
    OutputStream out;
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;
}
